package com.situ.mall.manager.controller.api;

import com.github.pagehelper.PageInfo;
import com.situ.mall.manager.entity.Category;
import com.situ.mall.manager.entity.Result;
import com.situ.mall.manager.service.CategoryService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

@RestController
//相当于controller注解与responsebody的结合体
//将当前的类放到spring的bean容器
//所有的处理器方法返回json格式的数据
@RequestMapping("/api/category")
//配置映射路径
//给当前所有处理器方法添加url映射的路径
public class APICategoryController {

    //自动注入service层对象
    @Resource
    private CategoryService categoryService;

    //添加
    @PostMapping    //添加需要用到post请求
    public Result add(@RequestBody Category category){
        //@RequestBody 解析客户端发来的json格式
        try {
            //添加成功
            int code = categoryService.add(category);
            return Result.success();
        } catch (Exception e) {
            //添加失败
            e.printStackTrace();
            return Result.error(e.getMessage());
        }
    }

    //删除
    @DeleteMapping
    public Result remove(Integer id){
        try {
            int code = categoryService.remove(id);
            return Result.success();
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(e.getMessage());
        }
    }

    //修改
    @PutMapping
    public Result edit(@RequestBody Category category) {
        try {
            int code = categoryService.edit(category);
            return Result.success();
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(e.getMessage());
        }
    }

    //根据条件查询
    @GetMapping
    public Result get(Integer page, Integer limit, Category category) {
        if (page == null) {
            List<Category> list = categoryService.search(category);
            return Result.success(list);
        } else {
            PageInfo pageInfo = categoryService.searchByPage(page, limit, category);
            return Result.success(pageInfo);
        }
    }


    //根据id进行查询
    //通过路径参数传递id 放在url上的参数
    @GetMapping("/{id}")
    public Result get(@PathVariable("id") Integer id){
        //@PathVariable("id")把上边路径的参数取出来 绑定id
        Category category = categoryService.getById(id);
        if(category == null){
            return Result.error("id不存在");
        }else{
            return Result.success(category);
        }
    }

}
